package com.myblog.controller.admin;

import com.myblog.entity.Category;
import com.myblog.service.CategoryService;
import com.myblog.enums.SysEnum;
import com.myblog.execption.SystemErrorException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@ApiModel("分类控制层")
@Controller
@RequestMapping("/admin")
public class CategoryController {

    private final static String ADMIN_CATEGORY = "admin/category";
    private final static String REDIRECT_LIST = "redirect:/" + ADMIN_CATEGORY;

    @Autowired
    private CategoryService categoryService;

    @ApiOperation("查询分类")
    @GetMapping("/category")
    public String list(Model model) {
        model.addAttribute("categoryList", categoryService.list());
        return ADMIN_CATEGORY;
    }

    @ApiOperation("保存分类")
    @PostMapping("/category")
    public String save0update(@Validated Category category, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new SystemErrorException(SysEnum.ILLEGAL_ERROR);
        }
        categoryService.save(category);
        return REDIRECT_LIST;
    }

    @ApiOperation("分类数据回显")
    @PutMapping("/category")
    @ResponseBody
    public Object listById(@RequestParam(value = "id", required = true) Integer id) {
        Category category = categoryService.listByCid(id);
        if (category == null) {
            throw new SystemErrorException(SysEnum.ILLEGAL_CATEGORY);
        }
        return category;
    }

    @ApiOperation("删除分类")
    @DeleteMapping("/category")
    public String del(@RequestParam(value = "id", required = true) Integer id) {
        categoryService.del(id);
        return REDIRECT_LIST;
    }
}
